package net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import dataprocess.DataProcessor;
import utils.Config;

public class UDPListener implements Runnable {

    private Config config;

    public UDPListener(Config config) {
        this.config = config;

    }

    private static final Logger logger = LogManager.getLogger(UDPListener.class);

    @Override
    public void run() {
        try (DatagramSocket socket = new DatagramSocket(config.getPort());) {
            while (true) {

                byte[] buf = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                try {
                    socket.receive(packet);
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    String data = new String(packet.getData()).trim();
                    logger.info("Received data at local port: "+socket.getLocalPort()+" from address:" + address + " port: " + port+". data:[" + data + "]" );
                    if (!data.isEmpty()) {
                        processData(data, config);
                    }

                } catch (IOException e) {
                    logger.error(e);
                }
            }
        } catch (SocketException e1) {
            logger.error(
                    "Exception:" + e1 + " Strat failed! Port: " + config.getPort() + " Type:" + config.getPortType());
            //e1.printStackTrace();
        }
    }

    private void processData(String data, Config config) {
        
        switch (config.getType()) {
        case "iueuav":
            DataProcessor.iueUAVMonitorDataProcess(data, config);
            break;
        case "iuewind":
            DataProcessor.iueWindDataProcess(data, config);
            break;
        case "iuesuperstation":
            DataProcessor.iueSuperStationProcess(data, config);
        default:
            break;
        }

    }

}
